﻿using System;
using System.Threading;
using System.Windows.Forms;
using AMM.CustomClassLibrary;

namespace AMM.UserControls {
    public partial class BaseControl : UserControl {

        public BaseControl() {
            this.InitializeComponent();
        }

        #region Protected members

        protected delegate void ThreadDelegate();
        protected delegate void ThreadDelegate<T>(T param1);

        protected void CreateNewThread(Action action, Action action1 = null) {
            Thread t = new Thread(new ThreadStart(() => {
                try {
                    action.Invoke();
                }
                catch (Exception ex) {
                    this.OperateException(ex);
                    this.ShowError(ex.Message);
                }
                finally {
                    if (action1 != null) {
                        this.UpdateUIElements(action1);
                    }
                }
            }));
            t.IsBackground = true;
            t.Start();
        }

        private void UpdateUIElements(Action action) {
            while (!this.IsHandleCreated) { this.CreateHandle(); }
            if (this.InvokeRequired) {
                this.Invoke(new ThreadDelegate<Action>(UpdateUIElements), action);
            }
            else {
                action.Invoke();
            }
        }

        protected void OperateException(Exception ex) {
            string msg = MethodHelper.ExtractExceptionMessage(ex);
            Logger.Error(msg);
        }

        protected DialogResult ShowError(string message) {
            return MessageBox.Show(message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }


        #endregion
    }
}
